package mspbots.data.manage.core;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.manage.annotation.ErrorResponse;
import mspbots.data.manage.annotation.RequestApiException;
import mspbots.data.manage.core.client.BaseClient;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Flux;

import java.util.Map;

/**
 * mspbots.data.manage.core.AppSerivceImpl
 *
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 * @date Created by 2020/10/22
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class AppServiceImpl {

    private final Map<String, BaseClient> clientMap;

    public Flux<JsonNode> get(Long tenantId, Map<String, Object> queryParams) {

        log.debug("This request params: {}", queryParams);
        String client = queryParams.get("client").toString();
        BaseClient baseClient = this.clientMap.getOrDefault(queryParams.get("client").toString(), null);
        if (ObjectUtils.isEmpty(baseClient)) {
            throw new RequestApiException(ErrorResponse.withErrors("This client [" + client + "] is empty, Please try again."));
        }
        String path = UriComponentsBuilder.fromPath(queryParams.get("path").toString()).build(tenantId).getPath();
        queryParams.remove("client");
        queryParams.remove("path");
        return baseClient.get(path, queryParams);

    }

    public Flux<JsonNode> post(Long tenantId, QueryBody queryBody) {

        log.debug("This request query body: {}", queryBody);

        BaseClient baseClient = this.clientMap.getOrDefault(queryBody.getClient(), null);
        if (ObjectUtils.isEmpty(baseClient)) {
            throw new RequestApiException("This [" + queryBody.getClient() + "] is empty, Please try again.");
        }
        String path = UriComponentsBuilder.newInstance().path(queryBody.getPath()).build(tenantId).getPath();
        return baseClient.post(path, queryBody.getParams());

    }
}
